package com.zhixin.fans.ks.ui.main.mutual;


import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhixin.fans.ks.KeyConstant;
import com.zhixin.fans.ks.R;
import com.zhixin.fans.ks.api.CoupleApi;
import com.zhixin.fans.ks.api.res.MutualContent;
import com.zhixin.fans.ks.manager.UserInfoManager;
import com.zhixin.fans.ks.ui.base.BaseDaggerFragment;

import org.eenie.common.subscribes.ProgressSubscriber;
import org.eenie.common.views.TopBarLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class MutualFragment extends BaseDaggerFragment implements BaseQuickAdapter.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    @BindView(R.id.top_bar)
    TopBarLayout mTopBar;
    @BindView(R.id.rv_mutual)
    RecyclerView mRvMutual;
    MutualAdapter mMutualAdapter;

    List<MutualContent> mMutuals = new ArrayList<>();


    CoupleApi mCoupleApi;
    UserInfoManager mUserInfoManager;
    @BindView(R.id.swiper)
    SwipeRefreshLayout mSwiper;

    Unbinder unbinder;

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            onRefresh();
        }
    };


    public MutualFragment(String title) {
        super(title);
    }

    @Override
    public int initContentView() {
        return R.layout.fragment_mutual;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mCoupleApi = getApplicationComponent().getApiManager().create(CoupleApi.class);
        mUserInfoManager = getCoupleAppComponent().getUserInfoManager();

    }

    @Override
    public void initUI(View rootView) {
        unbinder = ButterKnife.bind(this, rootView);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        mRvMutual.setLayoutManager(new LinearLayoutManager(mContext));
        mRvMutual.setAdapter(mMutualAdapter = new MutualAdapter(mMutuals));
        mMutualAdapter.setOnItemClickListener(this);

        mSwiper.setOnRefreshListener(this);

        LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver, new IntentFilter(KeyConstant.ACTION_UPDATE_MUTUAL));

        mMutualAdapter.setEnableLoadMore(true);
        mMutualAdapter.setOnLoadMoreListener(this, mRvMutual);

        mTopBar.addRightImageButton(R.mipmap.ic_post_mutual, 0)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivityForResult(new Intent(mContext, PostMutualActivity.class), 1002);

                    }
                });

        onRefresh();
    }


    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        MutualContent content = (MutualContent) adapter.getItem(position);

        startActivity(new Intent(mContext, MutualDetailActivity.class).putExtra("mutual_content", JSON.toJSONString(content)));


    }


    private void fetchMutual(int index) {
        mCoupleApi.fetchMutual(mUserInfoManager.getValue().getU_id(), index)
                .subscribe(new ProgressSubscriber<List<MutualContent>>() {
                    @Override
                    public void onNext(List<MutualContent> mutualContents) {
                        if (mutualContents.size() < 20) {
                            mMutualAdapter.loadMoreEnd(true);
                        } else {
                            mMutualAdapter.loadMoreComplete();
                        }

                        mMutuals.addAll(mutualContents);
                        mMutualAdapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onFinish() {
                        mSwiper.setRefreshing(false);
                    }
                });
    }

    @Override
    public void onDestroy() {
        LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        mMutuals.clear();
        mMutualAdapter.setNewData(mMutuals);
        mMutualAdapter.setEnableLoadMore(true);
        fetchMutual(mMutuals.size());
    }

    @Override
    public void onLoadMoreRequested() {
        fetchMutual(mMutuals.size());
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }



}
